package com.server.service.impl;

import java.util.List;

import com.bean.Product;
import com.server.dao.ProductDao;
import com.server.dao.impl.ProductDaoImpl;
import com.server.service.ProductService;

public class ProductServiceImpl implements ProductService {
	
	private ProductDao dao;
	
	public ProductServiceImpl() {
		super();
		this.dao = new ProductDaoImpl();
	}

	@Override
	public List<Product> findAll() {
		return dao.findAll();
	}

	@Override
	public void newProduct(Product p) {
		dao.newProduct(p);
	}

	@Override
	public void addQuantity(Product p) {

	}

	@Override
	public Product findById(Product product) {
		String id = product.getId();
		List<Product> allProducts = dao.findAll();
		for (Product p : allProducts) {
			if(p.getId().equals(id)) {
				return p;
			} 
		}
		return product;
	}
	
	@Override
	public Product updataQuantity(int operator, Product product) {
		int quantity = Integer.valueOf(product.getQuantity());
		if(quantity <= 0) {
		} else {
			List<Product> allProducts = findAll();
			for (Product serverProduct : allProducts) {
				if(serverProduct.getId().equals(product.getId())) {
					int serverQuantity = Integer.valueOf(serverProduct.getQuantity());
					int result = 0;
					switch (operator) {
					case 0:
						result = quantity + serverQuantity;
						break;
					case 1:
						int cut = serverQuantity - quantity;
						result = cut >= 0 ? cut : -1;
						break;
					}
					if(result != -1) {
						product.setQuantity(String.valueOf(result));
					}
					dao.updataQuantity(product);
					return findById(product);
				} 
			}
		}
		return product;
		
	}

}
